const Koa = require('koa'); // koa
const app = new Koa(); // 实例
const router = require('@koa/router')() // 路由
const bodyParser = require('koa-bodyparser'); // 接收post传参
const cors = require('koa-cors') // 解决跨域
const svgCaptcha = require('svg-captcha') // 验证码
const global = require('./utils/mysql') // 数据库
const { crypto } = require('./utils/crypto') // 加密
const jwt = require('jsonwebtoken') // 生成token

let captchas = " "; // 验证码

// 验证码
router.get('/getcaptcha', async ctx => {
    var captcha = svgCaptcha.create({ // 创建验证码
        size: 4,
        noise: 5,
        color: true,
        background: "#fff",
        width: 100,
        height: 50,
        fontSize: 50
    });
    captchas = captcha.text; // 赋值给全局变量保存
    ctx.response.type = 'svg'; // 不支持html5的svg格式，所以这里使用svg的形式返回验证码到客户
    ctx.body = captcha.data; // 添加标签
})

// 登录
router.post('/login', async ctx => {
    let { name, pwd, captcha } = ctx.request.body; // 获取参数

    // 判断用户是否存在
    let result = await global.query(`select * from user where name = '${name}'`)
    console.log(result);
    if (result.length == 0) {
        ctx.body = {
            code: 1,
            msg: '用户不存在 请先注册！'
        }
        return;
    }

    // 判断密码是否正确
    let results = await global.query(`select * from user where pwd = '${crypto(pwd)}'`)
    if (results.length == 0) {
        ctx.body = {
            code: 2,
            msg: '密码不正确！'
        }
        return;
    }

    // 验证验证码是否正确，如果错误，则返回错误信息。 如果正确，则执行登录
    if (captcha.toUpperCase() != captchas.toUpperCase()) {
        ctx.body = {
            code: 0,
            msg: "验证码不一致"
        }
        return;
    }

    // 全部满足条件则登录
    let res = await global.query(`select * from user where name = '${name}' and pwd = '${crypto(pwd)}'`)

    // 创建token令牌
    let token = jwt.sign({
        id: res[0].id,
        name: res[0].name,
    }, 'byp', { expiresIn: '1h' })

    // 返回登录成功
    if (res.length > 0) {
        ctx.body = {
            code: 3,
            msg: '登录成功！',
            uid: res[0].id,
            token
        }
    } else {
        ctx.body = {
            code: 4,
            msg: '登录失败！',
        }
    }
})

// 注册
router.post('/register', async (ctx) => {
    let { name, pwd } = ctx.request.body; // 获取参数

    // 判断该用户是否存在
    let result = await global.query(`select * from user where name = '${name}'`)
    if (result.length == 1) {
        ctx.body = {
            code: 5,
            msg: '用户已存在！'
        }
        return;
    }

    // 不存在则注册
    let res = await global.query(`insert into user(name,pwd) values ('${name}','${crypto(pwd)}')`)
    if (res.affectedRows == 1) {
        ctx.body = {
            code: 6,
            msg: '注册成功！'
        }
    } else {
        ctx.body = {
            code: 7,
            msg: '注册失败！'
        }
    }
})

// 注册成功之后接着登录

// 获取所有的数据
router.get('/books', async ctx => {
    let res = await global.query(`select * from books`)
    ctx.body = {
        code: 1,
        msg: "获取成功",
        data: res
    }
})

// 分页查询数据的接口
router.post('/books/list', async ctx => {
    let { page, pagesize } = ctx.request.body;

    let offect = (page - 1) * pagesize;

    let res = await global.query(`select * from books limit ${offect},${pagesize}`)
    ctx.body = {
        code: 1,
        msg: "获取成功",
        data: res,
    }
})

// 搜索的接口
router.post('/books/search', async ctx => {
    let { bookname, author } = ctx.request.body;

    let sql = `select * from books where 1 = 1 `

    if (bookname != '') {
        sql += ` and bookname = "${bookname}"`
    }
    if (author != '') {
        sql += ` and author = "${author}"`
    }

    console.log(sql);

    let res = await global.query(sql)
    ctx.body = {
        code: 1,
        msg: "获取成功",
        data: res,
    }
})

// 新增的接口
router.post('/books/add', async ctx => {
    let { bookname, author, type, num } = ctx.request.body;

    let res = await global.query(`insert into books (bookname,author,type,num) values ('${bookname}','${author}','${type}',${num})`)
    ctx.body = {
        code: 1,
        msg: "新增成功",
    }
})

// 修改的接口
router.post('/books/edit', async ctx => {
    let { editid, bookname, author, type, num } = ctx.request.body;

    let res = await global.query(`update books set bookname = '${bookname}',author = '${author}',type = '${type}',num = ${num} where id = ${editid}`)
    ctx.body = {
        code: 1,
        msg: "修改成功",
    }
})

// 删除的接口
router.post('/books/delete', async ctx => {
    let { delid } = ctx.request.body;

    let res = await global.query(`delete from  books where id = ${delid}`)
    ctx.body = {
        code: 1,
        msg: "删除成功",
    }
})

app.use(cors())
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(4000, () => {
    console.log("http://localhost:4000 后台服务器启动成功");
});